<template>
  <div>
    <div v-if="!isChatOpen" class="chat-icon" @click="openChatWindow">
      💬
    </div>
    <div
      v-if="isChatOpen"
      ref="chatWindowRef"
      :class="['chat-window', { minimized: isMinimized, maximized: isMaximized }]"
      :style="{
        position: 'fixed', // 修改为 fixed 定位
        right: rightPosition + 'px',
        bottom: bottomPosition + 'px',
        width: windowWidth + 'px',
        height: windowHeight + 'px'
      }"
    >
      <div
        class="chat-header"
        @mousedown="onHeaderMouseDown"
        @dblclick="handleHeaderDblClick"
      >
        <span style="color: #fff;"
          >{{ isSettingsOpen? '设置' : 'AI助手' }}</span
        >
        <div class="chat-header-buttons">
          <button v-if="isMinimized" @click="toggleMinimize">还原</button>
          <button v-else @click="toggleMinimize">最小化</button>
          <button v-if="!isMinimized" @click="toggleMaximizeButton">
            {{ isMaximized? '恢复' : '最大化' }}
          </button>
          <button v-if="!isMinimized" @click="handleCloseChatWindow">
            关闭
          </button>
          <button v-if="!isMinimized &&!isSettingsOpen" @click="openSettings">
            设置
          </button>
          <button v-if="isSettingsOpen" @click="closeSettings">返回</button>
          <button v-if="!isMinimized" @click="togglePin">
            {{ isPinned? '取消固定' : '固定位置' }}
          </button>
        </div>
      </div>
      <ChatBox
        v-if="!isMinimized &&!isSettingsOpen"
        :chatMessages="chatMessages"
        v-model:inputMessage="inputMessage"
        :windowWidth="windowWidth"
        :chatMessagesMaxHeight="chatMessagesMaxHeight"
        @sendMessage="sendMessage"
        @sendInputHeight="handleInputHeight"
      />
      <SettingWindow v-if="isSettingsOpen" />
      <div v-if="errorMessage">{{ errorMessage }}</div>
      <div
        class="resize-corner"
        :class="{ 'resize-corner-disabled': isPinned }"
        @mousedown="startResize"
        :style="{ bottom: resizeCornerBottom + 'px', right: resizeCornerRight + 'px' }"
      ></div>
    </div>
  </div>
</template>

<script setup>
  import { ref, onMounted, onUnmounted, nextTick, watch } from 'vue'
  import { setupWindowInteractions } from '../assets/windowInteractions.js'
  import SettingWindow from './SettingWindow.vue'
  import ChatBox from './ChatBox.vue'
  import { useApiStore } from '../store/api'

  const isChatOpen = ref(false)
  const isMinimized = ref(false)
  const isMaximized = ref(false)
  const isSettingsOpen = ref(false)
  const chatMessages = ref([])
  const inputMessage = ref('')
  const isPinned = ref(false)
  const chatWindowRef = ref(null)
  const rightPosition = ref(20) // 右侧距离
  const bottomPosition = ref(20) // 底部距离
  const errorMessage = ref('')
  const windowWidth = ref(400)
  const windowHeight = ref(500)
  const resizeCornerRight = ref(0)
  const resizeCornerBottom = ref(0)
  const chatMessagesMaxHeight = ref(0)
  const inputHeight = ref(0)

  const initialWidth = 400
  const initialHeight = 500
  const initialRight = 20
  const initialBottom = 20

  const apiStore = useApiStore()

  const openChatWindow = () => {
    isChatOpen.value = true
    windowWidth.value = initialWidth
    windowHeight.value = initialHeight
    rightPosition.value = initialRight
    bottomPosition.value = initialBottom
  }

  const openSettings = () => {
    isSettingsOpen.value = true
  }

  const closeSettings = () => {
    isSettingsOpen.value = false
  }

  const togglePin = () => {
    isPinned.value = !isPinned.value
  }

  const {
    onHeaderMouseDown,
    toggleMinimize,
    toggleMaximize,
    closeChatWindow,
    startResize,
    resizeWindow,
    endResize,
    sendMessage
  } = setupWindowInteractions(
    chatWindowRef,
    isMinimized,
    isMaximized,
    isPinned,
    rightPosition,
    bottomPosition,
    windowWidth,
    windowHeight,
    inputMessage,
    chatMessages,
    apiStore,
    errorMessage,
    initialWidth,
    initialHeight,
    initialRight,
    initialBottom
  )

  const handleCloseChatWindow = () => {
    // 弹出确认弹窗
    const confirmResult = confirm('确定要关闭聊天窗口吗？')
    if (confirmResult) {
      // 用户点击了确定，执行后续步骤
      closeChatWindow()
      isChatOpen.value = false
      isSettingsOpen.value = false
      chatMessages.value = []
      const chatHistoryId = localStorage.getItem('chat_history_id')
      if (chatHistoryId) {
        localStorage.removeItem('chat_history_id')
      }
    } else {
      // 用户点击了取消，不执行后续步骤
      console.log('用户取消了操作')
    }
  }

  const updateResizeCornerPosition = () => {
    // 这里可能需要根据实际情况调整
  }

  const updateChatMessagesHeight = () => {
    nextTick(() => {
      if (chatWindowRef.value) {
        const headerHeight = chatWindowRef.value.querySelector('.chat-header')
          .offsetHeight
        chatMessagesMaxHeight.value =
          windowHeight.value - headerHeight - inputHeight.value
      }
    })
  }

  const handleHeaderDblClick = () => {
    toggleMaximize()
  }

  const toggleMaximizeButton = () => {
    toggleMaximize()
  }

  const handleInputHeight = height => {
    inputHeight.value = height
    updateChatMessagesHeight()
  }

  const handleWindowResize = () => {
    // 保持弹窗固定在浏览器右侧和底部
    const maxRight = window.innerWidth - windowWidth.value
    const maxBottom = window.innerHeight - windowHeight.value
    rightPosition.value = Math.min(initialRight, maxRight)
    bottomPosition.value = Math.min(initialBottom, maxBottom)

    if (isMaximized.value) {
      windowWidth.value = window.innerWidth
      windowHeight.value = window.innerHeight
      rightPosition.value = 0
      bottomPosition.value = 0
      updateChatMessagesHeight()
      updateResizeCornerPosition()
    } else {
      // 保持弹窗顶部距离浏览器顶部的高度不变
      const initialChatWindowTop =
        window.innerHeight - (bottomPosition.value + windowHeight.value)
      bottomPosition.value =
        window.innerHeight - windowHeight.value - initialChatWindowTop
    }
  }

  onMounted(async () => {
    const container = document.getElementById('chat-widget-container')
    if (container) {
      container.style.pointerEvents = 'auto'
      container.style.position = 'fixed'
      container.style.zIndex = '9999'
      container.style.right = '0'
      container.style.bottom = '0'
      container.style.width = 'auto'
      container.style.height = 'auto'
      container.style.overflow = 'visible'
    }
    await apiStore.getModelList()
    await apiStore.getAppKeyInfo()
    window.addEventListener('resize', handleWindowResize)
  })

  onUnmounted(() => {
    window.removeEventListener('resize', handleWindowResize)
  })

  watch(
    [windowWidth, windowHeight, isMinimized, isMaximized, isChatOpen],
    () => {
      if (chatWindowRef.value && isChatOpen.value) {
        updateChatMessagesHeight()
      }
    }
  )
</script>

<style scoped>
  .chat-icon {
    position: fixed;
    right: 20px;
    bottom: 20px;
    background-color: #007bff;
    color: white;
    width: 50px;
    height: 50px;
    border-radius: 50%;
    display: flex;
    justify-content: center;
    align-items: center;
    cursor: pointer;
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.2);
    z-index: 9999;
  }

  .chat-window {
    border: 1px solid #ccc;
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.2);
    display: flex;
    flex-direction: column;
    z-index: 9999;
  }

  .chat-window.minimized {
    height: 30px;
    overflow: hidden;
  }

  .chat-window.maximized {
    right: 0;
    bottom: 0;
    width: 100vw;
    height: 100vh;
    box-sizing: border-box;
    overflow: auto;
  }

  .chat-header {
    background-color: #007bff;
    /* height: 20px; */
    padding: 10px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    cursor: move;
  }

  .chat-header-buttons button {
    margin-left: 5px;
  }

  .resize-corner {
    position: absolute;
    width: 5px;
    height: 5px;
    background-color: transparent;
    cursor: nwse-resize;
  }

  .resize-corner-disabled {
    cursor: default;
    pointer-events: none;
  }
</style>
